//
//  BitmapUtil.m
//  YHOCR
//
//  Created by 杨杨子 on 2018/7/25.
//  Copyright © 2018年 杨杨子. All rights reserved.
//

#import "BitmapUtil.h"
#import "PublicTool.h"

@implementation BitmapUtil
/**
 * 在二值图中获取黑色占比
 */
-(float)getBlackPercentFromBinary:(UIImage *)bitmap{
    UIImage *erImage = [self gray2Binary:bitmap];//二值化
    int width = erImage.size.width;
    int height = erImage.size.height;
    NSInteger count = 0;
    for (NSInteger x = 0; x < width; x ++) {
        for (NSInteger y = 0; y < height; y ++) {
            CGPoint pp = CGPointMake(x, y);
            UIColor *ppColor = [PublicTool colorAtPixel:pp WithImage:erImage];
           double colorNUm = [[PublicTool numberHexString:[[PublicTool hexFromUIColor:ppColor] substringFromIndex:1]] doubleValue];
            if (colorNUm < 16777215 / 2.0) {//16777215白色的数值，取色有误差，故比大小
                count ++;//黑色
            }
        }
    }
    return  (float)count/(width * height);//(width * height);//(float)count;//
}
/**
 二值化
 */
- (UIImage *)gray2Binary:(UIImage *)bitmap{
    
    CGSize size =[bitmap size];
    int width =size.width;
    int height =size.height;
    
    //像素将画在这个数组
    uint32_t *pixels = (uint32_t *)malloc(width *height *sizeof(uint32_t));
    //清空像素数组
    memset(pixels, 0, width*height*sizeof(uint32_t));
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    //用 pixels 创建一个 context
    CGContextRef context =CGBitmapContextCreate(pixels, width, height, 8, width*sizeof(uint32_t), colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast);
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), [bitmap CGImage]);
    int tt =1;
    CGFloat intensity;
    int bw;
    
    for (int y = 0; y <height; y++) {
        for (int x =0; x <width; x ++) {
            uint8_t *rgbaPixel = (uint8_t *)&pixels[y*width+x];
            intensity = (rgbaPixel[tt] + rgbaPixel[tt + 1] + rgbaPixel[tt + 2]) / 3. / 255.;
            
            bw = intensity > 0.45?255:0;
            
            rgbaPixel[tt] = bw;
            rgbaPixel[tt + 1] = bw;
            rgbaPixel[tt + 2] = bw;
            
        }
    }
    
    // create a new CGImageRef from our context with the modified pixels
    CGImageRef image = CGBitmapContextCreateImage(context);
    
    // we're done with the context, color space, and pixels
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    free(pixels);
    // make a new UIImage to return
    UIImage *resultUIImage = [UIImage imageWithCGImage:image];
    // we're done with image now too
    CGImageRelease(image);
    
    return resultUIImage;
}


@end
